package cn.hinglo.gameclaw.data.interceptors;

import cn.hinglo.gameclaw.data.annotation.IgnoreToken;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @createTime: 2018/5/22
 * @author: HingLo
 * @description: 所有拦截的父类
 */
public abstract class BaseInterceptor implements HandlerInterceptor {
    private final String OPTIONS = "OPTIONS";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //若果是option请求，就直接返回响应了
        if (OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        HandlerMethod handlerMethod = null;
        if (handler instanceof HandlerMethod) {
            handlerMethod = (HandlerMethod) handler;
        }
        // 如果有IgnoreToken注解，就不用拦截 直接返回就好了
        if (handlerMethod != null && handlerMethod.hasMethodAnnotation(IgnoreToken.class)) {
            return true;
        }
        return this.preHandle(request, response, handler, handlerMethod);
    }


    /***
     * 拦截器具体的实现方法
     * @param request 请求对象
     * @param response 响应流对象
     * @param handler Object对象
     * @param handlerMethod  handlerMethod 对象
     * @return 是否通过
     * @throws Exception
     */
    abstract boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, HandlerMethod handlerMethod) throws Exception;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
